package org.xp.judgeplatform.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.xp.judgeplatform.util.JwtUtil;

import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于处理基于JWT的身份验证
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        // 获取Authorization请求头
        final String authHeader = request.getHeader("Authorization");
        
        // 如果请求头不包含Bearer token，则继续过滤器链
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 从请求头中提取JWT令牌
            String jwt = jwtUtil.extractTokenFromHeader(authHeader);
            
            if (jwt != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 从JWT令牌中获取用户名
                String username = jwtUtil.getUsernameFromToken(jwt);
                
                if (username != null) {
                    // 加载用户详情
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                    
                    // 验证JWT令牌
                    if (jwtUtil.validateAccessToken(jwt, userDetails)) {
                        // 创建身份验证令牌
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        
                        // 设置请求详情
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        // 将身份验证信息设置到SecurityContext
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        
                        // DEBUG级别：JWT验证成功（频繁操作，仅调试时需要）
                        log.debug("用户'{}'的JWT令牌验证成功", username);
                    }
                }
            }
        } catch (Exception e) {
            log.error("JWT令牌处理过程中发生错误: {}", e.getMessage());
        }

        // 继续过滤器链
        filterChain.doFilter(request, response);
    }
} 